package com.sample.andremion.musicplayer.music;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.MediaStore;
import android.widget.RemoteViews;

import com.sample.andremion.musicplayer.R;
import com.sample.andremion.musicplayer.activities.MusicActivity;
import com.sample.andremion.musicplayer.utils.MediaUtil;

import java.util.ArrayList;
import java.util.List;

import static com.sample.andremion.musicplayer.music.MusicContent.ITEMS;

/**
 * Created by G on 2016/7/9 0009.
 */

public class MusicControl {

    public static final int MODE_SUNXU = 1, MODE_RANDOM = 2;
    private static final String MUSIC = "MUSIC", MODE = "PLAY_MODE" , AUTO_PLAY = "AUTO_PLAY";

    private static Context mContext;
    public static PlayerService mService;

    private static boolean firstPlay = true;
    private static int mPlayMode;
    private static List<OnMusicChangeListener> onMusicChangeListeners = new ArrayList<>();
    private static int position = 0;
    private static final String INTENT_FILTER_TAG = "MusicNotifyClick";
    private static NotifyBroadcast notifyBroadcast;
    private static boolean isPlay = false;

    public static void Init(Context context) {
        mContext = context;
        setITEMS();
        // Bind to PlayerService
        Intent intent = new Intent(context, PlayerService.class);
        context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        getPlayMode();

        IntentFilter filter = new IntentFilter(INTENT_FILTER_TAG);
        notifyBroadcast = new NotifyBroadcast();
        mContext.registerReceiver(notifyBroadcast, filter);
    }

    public static boolean isPlay() {
        return isPlay;
    }

    public static int getPosition() {
        return position;
    }

    public static int getPlayPosition() {
        return mService != null && mService.mediaPlayer != null ? mService.mediaPlayer.getCurrentPosition() : -1;
    }

    public static int getDuration() {
        return mService != null && mService.mediaPlayer != null ? mService.mediaPlayer.getDuration() : -1;
    }

    public static void playStop() {
        if (mService.mediaPlayer.isPlaying()) {
            mService.pause();
            isPlay = false;
            setMusicNotification();
        } else {
            mService.play();
            isPlay = true;
            setMusicNotification();
        }
        if (onMusicChangeListeners.size() != 0) {
            for (OnMusicChangeListener listener : onMusicChangeListeners)
                listener.onPlayStatusChange();
        }
    }

    public static MusicContent.MusicItem getCurrentItem() {
        if (ITEMS == null || ITEMS.size() == 0)
            return null;
        return ITEMS.get(position);
    }

    public static boolean play(int p) {
        if (ITEMS == null)
            return false;
        int size = ITEMS.size();
        if (size <= 0)
            return false;
        firstPlay = false;
        p = p < size ? p : 0;
        MusicControl.position = p;
        MusicContent.MusicItem item = ITEMS.get(p);
        mService.playNewMusic(item.mUrl);

        isPlay = true;
        setMusicNotification();

        if (onMusicChangeListeners.size() != 0) {
            for (OnMusicChangeListener listener : onMusicChangeListeners)
                listener.onChange(item);
        }
        return true;
    }

    public static void setMusicChangeListener(OnMusicChangeListener listener) {
        onMusicChangeListeners.add(listener);
    }

    public static void removeMusicChangeListener(OnMusicChangeListener listener) {
        onMusicChangeListeners.remove(listener);
    }

    public interface OnMusicChangeListener {
        void onPlayStatusChange();
        void onChange(MusicContent.MusicItem item);
    }

    public static boolean isAutoPlay() {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(MUSIC, Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean(AUTO_PLAY, true);
    }

    public static void setAutoPlay(boolean auto) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(MUSIC, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean(AUTO_PLAY, auto).apply();
    }

    public static int getPlayMode() {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(MUSIC, Context.MODE_PRIVATE);
        mPlayMode = sharedPreferences.getInt(MODE, MODE_SUNXU);
        return mPlayMode;
    }

    public static void setPlayMode(int mode) {
        if (mode == mPlayMode)
            return;
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(MUSIC, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putInt(MODE, mode);
        edit.apply();
        mPlayMode = mode;
    }

    public static void nextMusic() {
        if (mPlayMode == MODE_SUNXU) {
            if (!firstPlay)
                position++;
        } else if (mPlayMode == MODE_RANDOM) {
            position = (int) (Math.random() * ITEMS.size());
        }
        play(position);
    }

    private static void setITEMS() {
        ITEMS = getMusicList();
    }

    private static boolean mBound;
    /**
     * Defines callbacks for service binding, passed to bindService()
     */
    private static ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to PlayerService, cast the IBinder and get PlayerService instance
            PlayerService.LocalBinder binder = (PlayerService.LocalBinder) service;
            mService = binder.getService();
            mBound = true;
            if (isAutoPlay()) {
                nextMusic();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName classname) {
            mBound = false;
        }
    };

    public static void unBindService() {
        if (notifyBroadcast != null)
            mContext.unregisterReceiver(notifyBroadcast);
        NotificationManager systemService = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        systemService.cancel(51);
    }

    public static void setMusicNotification() {
        RemoteViews remoteView = new RemoteViews(mContext.getPackageName(), R.layout.notify_music);
        MusicContent.MusicItem currentItem = getCurrentItem();
        if (currentItem == null)
            return;
        remoteView.setImageViewBitmap(R.id.image, MediaUtil.getArtwork(mContext, currentItem.mId, currentItem.mAlbumId, true, false));
        remoteView.setTextViewText(R.id.musicName, currentItem.mTitle);
        remoteView.setTextViewText(R.id.artName, currentItem.mArtist);

        if (isPlay) {
            remoteView.setImageViewResource(R.id.playStop, R.drawable.ic_pause_circle_outline_grey);
        } else {
            remoteView.setImageViewResource(R.id.playStop, R.drawable.ic_play_circle_outline_grey);
        }
        remoteView.setImageViewResource(R.id.next, R.drawable.ic_skip_next_grey);


        Intent playStatus = new Intent(INTENT_FILTER_TAG);
        playStatus.putExtra("button", 1);
        remoteView.setOnClickPendingIntent(R.id.playStop, PendingIntent.getBroadcast(mContext, 0, playStatus, PendingIntent.FLAG_UPDATE_CURRENT));

        Intent nextIntent = new Intent(INTENT_FILTER_TAG);
        nextIntent.putExtra("button", 2);
        remoteView.setOnClickPendingIntent(R.id.next, PendingIntent.getBroadcast(mContext, 1, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT));


        Intent intent = new Intent(mContext, MusicActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 2, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder = new Notification.Builder(mContext)
                .setSmallIcon(R.drawable.logo_outline);
        builder.setOngoing(true);
        builder.setPriority(Notification.PRIORITY_HIGH);
        builder.setContentIntent(pendingIntent);
        builder.setContent(remoteView);

        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(51, builder.build());
    }


    private static List<MusicContent.MusicItem> getMusicList() {
        Cursor cursor = mContext.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        List<MusicContent.MusicItem> mp3Infos = new ArrayList<MusicContent.MusicItem>();
        for (int i = 0; i < cursor.getCount(); i++) {
            MusicContent.MusicItem mp3Info = new MusicContent.MusicItem();
            cursor.moveToNext();
            long id = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media._ID));   //音乐id
            long album = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));   //音乐id
            String title = cursor.getString((cursor
                    .getColumnIndex(MediaStore.Audio.Media.TITLE)));//音乐标题
            String artist = cursor.getString(cursor
                    .getColumnIndex(MediaStore.Audio.Media.ARTIST));//艺术家
            long duration = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DURATION));//时长
            String url = cursor.getString(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DATA));              //文件路径
            int isMusic = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否为音乐
            if (isMusic != 0 && duration > 1000 * 20) {     //只把音乐且大于20s的添加到集合当中
                mp3Info.mDuration = duration / 1000;
                mp3Info.mTitle = title;
                mp3Info.mAlbumId = album;
                mp3Info.mUrl = url;
                mp3Info.mArtist = artist;
                mp3Info.mId = id;
                mp3Infos.add(mp3Info);
            }
        }
        return mp3Infos;
    }


    private static class NotifyBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int buttonType = intent.getIntExtra("button", -1);
            if (buttonType == 1)
                playStop();
            else if (buttonType == 2)
                nextMusic();
        }

    }
}
